package com.xx.library.service.impl;

import com.xx.library.entity.User;
import com.xx.library.mapper.UserMapper;
import com.xx.library.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    @Override
    public User getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }

    @Override
    public List<User> getUsersByCondition(User user) {
        return userMapper.selectByCondition(user);
    }

    @Override
    public void addUser(User user) {
        // 检查用户名是否已存在
        if (getUserByUsername(user.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        // 加密密码
//        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        userMapper.insert(user);
    }

    @Override
    public void updateUser(User user) {
//        // 如果修改了密码，需要加密
//        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
//            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
//        }
        userMapper.update(user);
    }

    @Override
    public void deleteUser(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public User login(String username, String password) {
        User user = getUserByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
//        // 验证密码
//        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
//            throw new RuntimeException("密码错误");
//        }
        if (!user.getPassword().equals(password)) {
            throw new RuntimeException("密码错误");
        }
        return user;
    }

    @Override
    public void register(User user) {
        // 设置默认角色和状态
        user.setRole("USER");
        user.setStatus(1);
        addUser(user);
    }
} 